<template>
    <div class="Voicebroadcast">
        <Head></Head>
        <div class="Voicebroadcast-content">
            <div class="Voicebroadcast-con-content">
                <div class="Voicebroadcast-info">
                    <div class="Voicebroadcast-info-left">
                        <span>{{gorunpName}}</span>
                        <label>
                            <span>{{LanguagCh}}</span>
                            <span>{{nicknames}}老师</span>
                        </label>
                    </div>
                    <div class="Voicebroadcast-info-right">
                        <span>当前在线({{OnlineNmuver}}人)</span>
                        <label @click="Exitto">退出直播间</label>
                    </div>
                </div>
                <div class="Voicebroadcast-contents">
                    <div class="Voicebroadcast-contents-left">
                        <div class="Voicebroadcast-avater">
                            <div>
                                <label>
                                    <img :src="theavaters" alt="">
                                </label>
                                <span>{{nicknames}}</span>
                            </div>
                            <ul>
                                <li id="id_test1">
                                    <img class="attachment" :src="avater1" alt="" v-if="avater1!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test2">
                                    <img class="attachment" :src="avater2" alt="" v-if="avater2!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test3">
                                    <img class="attachment" :src="avater3" alt="" v-if="avater3!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test4">
                                    <img class="attachment" :src="avater4" alt="" v-if="avater4!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test5">
                                    <img class="attachment" :src="avater5" alt="" v-if="avater5!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test6">
                                    <img class="attachment" :src="avater6" alt="" v-if="avater6!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test7">
                                    <img class="attachment" :src="avater7" alt="" v-if="avater7!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                                <li id="id_test8">
                                    <img class="attachment" :src="avater8" alt="" v-if="avater8!=''">
                                    <img class="noattachment" src="/images/图层 31 拷贝@2x.png" alt="" v-else>
                                </li>
                            </ul>
                        </div>
                        <div class="Voicebroadcast-footer">
                            <label>
                                <span>直播连线中 {{str}}</span>
                            </label>
                            <label class="attachment">
                                <!-- <span @click="Tolive" v-if="IsStarted == '0'">开播准备</span> -->
                                <span @click="Tolivecheactket" v-if="IsStarted == '1'">连线</span>
                                <span  v-else-if="IsStarted == '3'" style="display:none"></span>
                            </label>
                            <label>
                                <img src="/images/矩形 32@2x.png" alt="">
                                <img src="/images/矩形 33@2x (1).png" alt="">
                                <img src="/images/圆角矩形 27@2x.png" alt="">
                            </label>
                        </div>
                    </div>
                    <div class="Voicebroadcast-contents-right">
                        <div class="Systemmessage">
                            <p>系统消息：</p>
                            <p>欢迎来到直播间！Tmore提倡绿色健康直播。直播内容和评论内容严禁出现违法、违规、低俗色情、吸烟汹酒等内容，如有违反，将视情节严重程度对作者账号进行处罚。</p>
                        </div>
                        <ul class="MessageList" id="MessageList">
                            <li v-for="(messageitem,messindex) in ThemessageList" :key="messindex">
                                <span v-if="messageitem[0].nick == 0">啊哈哈</span>
                                <span v-else>{{messageitem[0].nick}}:</span>
                                
                                <span>{{messageitem[0].msg}}</span>
                            </li>
                        </ul>
                        <div class="messagefooter">
                            <label></label>
                            <div>
                                <textarea v-model="thetex" @keydown.enter="Tochat" name="" id=""></textarea>
                                <span @click="Tochat">发送</span>
                            </div>
                            
                        </div>
                    </div>
                </div>
                <div id="id_test_video" style="width:100%; height:auto;display:none"></div>
               <div style="display:none" v-for="(rooitem,roomindex) in roomdis" :key="roomindex" v-bind:id="rooitem.Id">
                 {{rooitem}}
               </div>
               <!-- <div id="id_test" ref="id_test" style="width:100%; height:auto"></div> -->
            </div>
            <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
                <span>{{toconname}}请求连麦</span>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="toallowed">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <Modal :show="show" :Theserver="Theserver" :Thekeys="Thekeys" :title="title" @hideModal="hideModal" @submit="submit">
            <span slot="Solt1" data-clipboard-text="Theserver" id="copys"> 
                OBS推流服务器：{{Theserver}}
            </span>
            <span slot="Solt2">
                OBS推流密钥：{{Thekeys}}
            </span>
        </Modal >
        <Footer></Footer>
    </div>
</template>
<script>
import {TimLogin} from '../../components/Tim'
import TIM from 'tim-js-sdk';
import Modal  from './Dialog';
import $ from 'jquery';
let options = {
  SDKAppID: 1400255047 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};
let tim = TIM.create(options); // SDK 实例通常用 tim 表示
import Head from '../../components/LiverHead'
import Footer from '../../components/footer'
var requestNum = 0;
var requestJoinCallback = null;
var bigAnchorStreamID = '';
var gTimeoutID = null;
var mTimeDiff = 0;
export default {
    name:'Voicebroadcast',
    data(){
        return{
            title: 'obs推流地址',
            show: false,
            conversationID:'',
            tim : TIM.create(options),
            item:'',
            avaters:'/images/图层 31 拷贝@2x.png',
            ThemessageList:[],
            thetex:'',
            unserinfo:JSON.parse(localStorage.getItem('userinfo')),
            gorunpName:'',
            nicknames:'',
            theavaters:'',
            languageEn:[
                {"Estonian":"爱沙尼亚语"},
				{"Arabic":"阿拉伯语"},
				{"Bulgarian":"保加利亚语"},
				{"polish":"波兰语"},
				{"Danish":"丹麦语"},
				{"German":"德语"},
				{"Russian":"俄语"},
				{"Traditional Chinese":"繁体中文"},
				{"French":"法语"},
				{"Finnish":"芬兰语"},
				{"Korean":"韩语"},
				{"Dutch":"荷兰语"},
				{"Czech":"捷克语"},
				{"romanian":"罗马尼亚语"},
				{"Portuguese":"葡萄牙语"},
				{"Japanese":"日语"},
				{"Swedish":"瑞典语"},
				{"slovenian":"斯洛文尼亚语"},
				{"Thai":"泰语"},
				{"Spanish":"西班牙语"},
				{"Greek":"希腊语"},
				{"hun":"匈牙利语"},
				{"Italian":"意大利语"},
				{"English":"英语"},
				{"Vietnamese":"越南语"},
				{"cantonese":"粤语"},
				{"Chinese":"中文"}
            ],
            LanguagCh:'',
            IsStarted:1,
            pushURL:'',
            Isattachment:false,

            //时间计时器
            hour:0,//时
            minute:0,//分
            ms:0,//秒
            second:0,
            time:'',
            str:'00:00:00',
            options:'',
            
            Theserver:'',//obs推流服务器地址
            Thekeys:'',//obs密钥地址
            player:null,
            dialogVisible:false,
            toconname:'',
            toids:'',
            heartds:'',

            //房间信息
            RoomInfoos:[],
            bigAnchorStreamID:[],
            roomdis:[],

            //连麦信息
            avater1:'',
            avater2:'',
            avater3:'',
            avater4:'',
            avater5:'',
            avater6:'',
            avater7:'',
            avater8:'',
            OnlineNmuver:1,
            isscenario:'',
            group_id:'',
            group_ids:'',
            group_name:'',
            languages:'',
            isfasong:true,
        }
    },
    created:function(){
        var its = this.$route.query.item
        this.isscenario = this.$route.query.isscenario
        this.item = JSON.parse(its)
        console.log( this.item,'88879977')
        if(this.isscenario){
            this.conversationID = "GROUP"+this.item.group_id
            this.group_id = this.item.id
            this.group_ids = this.item.group_id
            this.group_name = this.item.group_name
            this.languages = this.item.language
        }else{
            this.conversationID = "GROUP"+this.item.map.groupinfo.group_id
            this.group_id = this.item.map.groupinfo.id
            this.group_ids = this.item.map.groupinfo.group_id
            this.group_name = this.item.map.groupinfo.group_name
            this.languages = this.item.map.groupinfo.language
        }
    },
    mounted(){
        var _this = this
        if(_this.isscenario){
            _this.gorunpName = _this.item.group_name
            console.log(_this.item)
        }else{
            _this.gorunpName = _this.item.map.groupinfo.group_name
            console.log(_this.item)
        }
        _this.nicknames = _this.item.map.userinfo.nick_name
        _this.theavaters = _this.item.map.userinfo.avatar
        _this.Getonline()
        _this.languageEn.forEach(e=>{
            if(e[_this.languages]){
                _this.LanguagCh = e[_this.languages]
            }
        });
        TimLogin()
        setTimeout(function () {//延迟2s执行IM的获取消息等功能防止sdk报错
            _this.GethistoryMessage()
        },2000);
        setTimeout(function () {//进入直播间就加入群主
            let promise = _this.tim.joinGroup({ groupID: _this.group_ids, type: TIM.TYPES.GRP_AVCHATROOM });
            promise.then(function(imResponse) {
                switch (imResponse.data.status) {
                    case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: break; // 等待管理员同意
                    case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
                    console.log(imResponse.data.group); // 加入的群组资料
                    break;
                    default: break;
                }
                }).catch(function(imError){
                    console.warn('joinGroup error:', imError); // 申请加群失败的相关信息
                });
        },3000);
    },
    updated(){
        // 聊天定位到底部
          let ele = document.getElementById('MessageList');
          ele.scrollTop = ele.scrollHeight;
    },
    beforeDestroy(){//清除定时器等
        clearInterval(this.heartds)
        clearInterval(this.time)
        this.hour =0
        this.minute =0
        this.ms =0
        this.second =0
        this.str ='00:00:00'
    },
    methods:{
        GethistoryMessage(){
            var _this = this
            console.log('00')
            // 打开某个会话时，第一次拉取消息列表
            let promise = tim.getMessageList({conversationID:_this.conversationID, count: 10});
            promise.then(function(imResponse) {
                console.log('00')
                const messageListss = imResponse.data.messageList; // 消息列表。
                console.log(messageListss,'消息列表。')
                messageListss.forEach(e=>{
                    var payload = e.payload
                    if(payload.description ==''){
                        var payloads = JSON.parse(e.payload.data) 
                        var arrs = [
                            {
                                nick:payloads.userName,
                                msg:payloads.data.msg
                            }
                        ]
                        console.log(payloads,'ahhty')
                        _this.ThemessageList.push(arrs)
                    }
                })
            });
            let onMessageReceived = function(event) {
                console.log(event,'收到的消息s')
                event.data.forEach(e => {
                    var payload = JSON.parse(e.payload.data) 
                    if(payload.cmd == 'linkmic'){
                        console.log(payload.data,'????')
                        if(payload.data.roomID == _this.group_ids){
                            _this.dialogVisible = true
                            _this.toconname = payload.data.userName
                            _this.toids = payload.data.userID
                        }
                    }else{
                        console.log(_this.group_ids,'???==?')
                        if(e.to == _this.group_ids){
                            var arrs = [{
                                nick:payload.userName,
                                msg:payload.data.msg
                            }]
                            _this.ThemessageList.push(arrs)
                        } 
                    }
                   
                });
            };
            tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
        },
        Tochat(event){
            var _this = this
            if(_this.isfasong){
                _this.isfasong = false
                event.preventDefault();
                _this.thetex = _this.thetex.split(" ").join("");
                if(_this.thetex .length== 0){
                    _this.$message({
                        message: '不能发送空消息',
                        type: 'warning'
                    });
                    _this.isfasong = true
                }else{
                    var data ={
                            cmd:'CustomCmdMsg',
                            data:{
                                cmd:'1',
                                msg:_this.thetex,
                            },
                            userName:_this.unserinfo.nick_name
                    }
                    let message = tim.createCustomMessage({
                        to: _this.group_ids,
                        conversationType: TIM.TYPES.CONV_GROUP,
                        payload: {
                            text: _this.thetex,
                            data:JSON.stringify(data)
                        }
                    });
                    let promise = tim.sendMessage(message);
                    promise.then(function(imResponse) {// 发送成功
                        _this.thetex =''
                        _this.isfasong = true
                        var as = [imResponse.data.message]
                        as.forEach(e=>{
                            var payload = JSON.parse(e.payload.data) 
                            var arrs = [
                                {
                                    nick:_this.unserinfo.nick_name,
                                    msg:payload.data.msg
                                }
                            ]
                            _this.ThemessageList.push(arrs)
                        })
                    }).catch(function(imError) {//发送失败
                    });
                }
            }
            
        },
        toallowed(){
            var _this = this
            var mTimeDiff = 0;
            var data ={
                    cmd:'linkmic',                   
                    data:{
                        joinIndex:'',
                        roomID:_this.group_ids,
                        type:'response',
                        result: 'accept',
                        timestamp: Math.round(Date.now()) - mTimeDiff,
                        userID:_this.unserinfo.user_id,
                        userName:_this.unserinfo.nick_name,
                        userAvatar:_this.unserinfo.avatar,
                        reason: '',
                    },
            }
            let message = tim.createCustomMessage({
                to: _this.toids,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    data:JSON.stringify(data)
                }
            });
            let promise = tim.sendMessage(message);
            promise.then(function(imResponse) {// 发送成功
                console.log(imResponse,'000')
                _this.dialogVisible = false
                _this.Toheart()
            }).catch(function(imError) {//发送失败
                console.log(imError,'999')
            });
        },
        Getonline(){//获取在线人数列表以及在线人数数量
            var data ={
                group_id :this.item.id,
                pageSize:30,
            }
            this.$axios({
                method:'GET',
                url:'http://101.37.66.151:8768/eg-api/message/messageJoinGroup/queryOnlineCount',
                params:data,
            }).then((res) =>{
                this.OnlineNmuver = res.data.data.onlineCount
            }).catch((error) =>{
                console.log(error)
            })
        },
        handleClose(done) {
            this.$confirm('确认关闭？').then(_ => {
                done();
            }).catch(_ => {});
        },
        Exitto(){
            this.$router.go(-1)
            clearInterval(this.time)
            this.hour =0
            this.minute =0
            this.ms =0
            this.second =0
            this.str ='00:00:00'
        },
        Tolive(){
            var  date1 =new Date();
            var sd = Date.parse(date1)
            var data ={
                userID:this.unserinfo.user_id,
                roomID:this.group_ids,
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/get_anchor_url',
                params:data,
                data: {
                    userID:this.unserinfo.user_id,
                    roomID:this.group_ids,
                },
            }).then((res) =>{
                if(res.data.code == 202001){
                    this.$message.error('token已经失效请重新登录');
                }else{
                    this.Theserver =res.data.pushURL.substring(0,40)
                    this.Thekeys = res.data.pushURL.substring(40,200)
                    this.pushURL = res.data.pushURL
                    this.show = true
                    this.IsStarted = '1'
                    this.Tolives()
                } 
            }).catch((error) =>{
                console.log(error)
            })
        },
        Tolives(){
            var createRoomInfo = {
                userID: this.unserinfo.user_id,
		        roomInfo: {
                    roomID:this.group_ids,
                    pushURL: this.pushURL,
                    roomInfo:this.item.map.groupinfo.group_name
                },
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/create_room',
                params:createRoomInfo,
                data: {
                    userID:this.unserinfo.user_id,
                    roomID:this.group_ids,   
                },              
            }).then((res) =>{
                if(res.data.message == "Success!"){
                    var td = {
                        roomID: this.group_ids,
                        userID: this.unserinfo.user_id,
                        userName: this.unserinfo.nick_name,
                        userAvatar:this.unserinfo.avatar,
                        pushURL: this.pushURL,
                        token:localStorage.getItem('token')
                    }
                this.$axios({
                    method:'post',
                    url:'https://liveroom.qcloud.com/weapp/live_room/add_anchor',
                    params:td,
                    data: td,              
                }).then((res) =>{
                    console.log(res.data,'房间成功')
                    var roominfos = {
                        roomID : this.group_ids,
                        userID: this.unserinfo.user_id,
                        token:localStorage.getItem('token')
                    }
                    this.$axios({
                        method:'post',
                        url:'https://liveroom.qcloud.com/weapp/live_room/get_anchors',
                        params:roominfos,
                        data: roominfos,              
                        }).then((res) =>{
                            console.log(res.data,'房间信息')
                            this.RoomInfoos= res.data
                            this.Gethears(res.data)
                        }).catch((error) =>{
                            console.log(error)
                        })
                    }).catch((error) =>{
                        console.log(error)
                    })
                }
            }).catch((error) =>{
                console.log(error)
            })
        },
        Tolivecheactket(){
            var _this = this
            var data = {
                userID:_this.unserinfo.user_id,
                token:localStorage.getItem('token'),
            }
            _this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/get_room_list',
                params:data,
                data: {cnt:10},              
            }).then((res) =>{
                console.log(res.data,'房间列表')
                res.data.rooms.forEach(e=>{
                    TimLogin()
                    console.log(_this.group_ids,'??')
                    if(e.roomID == _this.group_ids){
                        console.log('=>')
                        var mixedPlayURL = e.mixedPlayURL
                        mixedPlayURL = mixedPlayURL.replace('flv', "m3u8")
                        var player = new TcPlayer('id_test_video', {
                            m3u8: mixedPlayURL,
                            flv: e.mixedPlayURL,
                            autoplay:true,
                            width:'480',
                            height:'400',
                            listener:function(msg){
                                if(msg.type == 'play'){
                                    _this.IsStarted = '3'
                                    _this.timeStart()
                                    _this.Toheart()
                                }else if(msg.type == 'error'){
                                    $('#id_test_video').html("");
                                    _this.time =setInterval(this.timer,50)
                                    _this.player.dispose()
                                    clearInterval(this.time)
                                    this.hour =0
                                    this.minute =0
                                    this.ms =0
                                    this.second =0
                                    this.str ='00:00:00'
                                    alert("主播未开播")
                                }
                            }
                        });  
                    }
                })
                
            }).catch((error) =>{
                console.log(error)
            })
        },
        timeStart(){
            this.time =setInterval(this.timer,50)
        },
        Toheart(){
            this.heartds = setInterval(this.Heatr,7000)
        },
        Heatr(){
            var data ={
                roomID:this.group_ids,
                userID:this.unserinfo.user_id,
                roomStatusCode:'',
                token:localStorage.getItem('token')
            }
            this.$axios({
                    method:'post',
                    url:'https://liveroom.qcloud.com/weapp/live_room/anchor_heartbeat',
                    params:data,
                    data: data,              
                }).then((res) =>{
                    console.log(res.data,'房间成功')
                    if(res.data.code){
                        console.log('心跳失败')
                    }else if(res.data.pushers){
                        console.log(res.data.pushers,'房间主播信息')
                        if(res.data.pushers.length ==1){
                            this.avater1 = ''
                            this.avater2 = ''
                            this.avater3 = ''
                            this.avater4 = ''
                            this.avater5 = ''
                            this.avater6 = ''
                            this.avater7 = ''
                            this.avater8 = ''
                        }else{
                            this.avater1 = ''
                            this.avater2 = ''
                            this.avater3 = ''
                            this.avater4 = ''
                            this.avater5 = ''
                            this.avater6 = ''
                            this.avater7 = ''
                            this.avater8 = ''
                            for(var i=1;i<res.data.pushers.length;i++){
                                this['avater' + i] = res.data.pushers[i].userAvatar
                            }
                        }  
                        this.Gethears(res.data)
                    }                     
                }).catch((error) =>{
                    console.log(error)
                })
        },
        Gethears(data){
            /**
             * enterPushers：新进推流人员信息
             * leavePushers：退出推流人员信息
             * ishave：用于判断去重操作
            */
           var _this = this
           var enterPushers = [],
		        leavePushers = [],
                ishave = 0;
            
            data.pushers.forEach(function(val1){  
                ishave = 0;
                _this.RoomInfoos.pushers.forEach(function(val2){
                    if(val1.userID == val2.userID){
                        ishave = 1;
                    }
                });
                if(!ishave && val1.userID != _this.unserinfo.user_id){
                    enterPushers.push(val1);
		            ishave = 0;
                }
            })
            _this.RoomInfoos.pushers.forEach(function(val1){
                ishave = 0;
                data.pushers.forEach(function(val2){
                    if(val1.userID == val2.userID) {
			            ishave = 1;
		            }
                });
                if(!ishave){
                    leavePushers.push(val1);
                    ishave = 0;
                };
            })
            _this.RoomInfoos.pushers = data.pushers;
            if(enterPushers.length) {
                console.log('进房ss:', JSON.stringify(enterPushers));
                enterPushers.forEach(e=>{
                    var streamID = _this.getStreamIDByStreamUrl(e.accelerateURL);
                    e.Id = streamID
                    _this.roomdis.push(e)
                    if(e.userID == _this.unserinfo.user_id){
                    }else{
                        _this.roomdis.forEach(i=>{
                            var url ="http://live.curiousmore.com/live/"+streamID+'.m3u8'
                            var player = new TcPlayer(i.Id, {
                                m3u8: url,
                                autoplay:true,
                                width:'110',
                                height:'100',
                            }); 
                        })
                    }
                })
                this.mergeStream(1);
                
            }
            // 通知有人退出房间
            if(leavePushers.length) {
                console.log('退房:', JSON.stringify(leavePushers));
                leavePushers.forEach(e=>{
                    var streamID = _this.getStreamIDByStreamUrl(e.accelerateURL);
                    e.Id = streamID
                    _this.roomdis.push(e)
                    $(streamID).html("");
                })
               this.mergeStream(1)
            }
        },
        timer(){
            this.ms =this.ms +50
            if (this.ms >=1000) {
                this.ms =0
                this.second =this.second +1
            }
            if (this.second >=60) {
                this.second =0
                this.minute =this.minute +1        //分钟
            }
            if (this.minute >=60) {
                this.minute =0
                this.hour =this.hour +1        //小时
            }
            this.str =this.toDub(this.hour) +':' +this.toDub(this.minute) +':' +this.toDub(this.second)/*+""+this.toDubms(this.ms)+"毫秒"*/
        },
        toDub(n){//补0操作
            if (n <10) {
                return '0' + n
            }else {
                return '' + n
            }
        },
        hideModal() {
            // 取消弹窗回调
            this.show = false
        },
        mergeStream(retryCount){//混流
            var _this = this
            var mergeStreams = [];
            if(_this.RoomInfoos.pushers.length > 0) {
                _this.RoomInfoos.pushers.forEach(function (val) {
                    if (val.userID != _this.RoomInfoos.roomCreator) {//获取流id
                        console.log('=>>>')
                        var streamID = _this.getStreamIDByStreamUrl(val.accelerateURL);
                        if (streamID) {
                            console.log('=>')
                            mergeStreams.push({
                                userID: val.userID,
                                streamID: streamID,
                                width: val.width,
                                height: val.height
                            });
                        }
                    } else {
                        _this.bigAnchorStreamID = _this.getStreamIDByStreamUrl(val.accelerateURL);
                    }
                });
	        }
            console.log("混流信息:", JSON.stringify(mergeStreams));
            _this.sendStreamMergeRequest(retryCount, mergeStreams);
        },
        getStreamIDByStreamUrl(streamUrl){
            if (!streamUrl) {
                return null;
            }
            var subStr = streamUrl;
            var index = subStr.indexOf('?');
            if (index >= 0) {
                subStr = subStr.substring(0, index);
            }
            if (!subStr) {
                return null;
            }
            index = subStr.lastIndexOf('/');
            if (index >= 0) {
                subStr = subStr.substring(index + 1);
            }
            if (!subStr) {
                return null;
            }
            index = subStr.indexOf('.');
            if (index >= 0) {
                subStr = subStr.substring(0, index);
            }
            if (!subStr) {
                return null;
            }
            return subStr;
        },
        sendStreamMergeRequest(retryCount, mergeStreams) {
            var _this = this
            if (retryCount < 0) {
                return;
            }
            var mergeInfo = this.createMergeInfos(mergeStreams);
            console.log('混流信息:', JSON.stringify(mergeInfo));
            this.doMergeRequest(mergeInfo, function (ret) {
                console.log(ret,'123321')
                if (ret) {
                    console.log('混流成ssss功');
                    console.log(_this.RoomInfoos,'什么啊')
                    
                } else {
                    console.log('混流失败9999');
                    setTimeout(() => {
                        retryCount--;
                        this.sendStreamMergeRequest(retryCount, mergeStreams);
                    }, 2000);
                }
            });
        },
        createMergeInfos(mergeStreams) {
            console.log("混流原始信息:", JSON.stringify(mergeStreams));
            var smallAnchorWidth = 160;
            var smallAnchorHeight = 240;
            var bigAnchorWidth = 360;
            var bigAnchorHeight = 640;
            var offsetHeight = 90;
            if (bigAnchorWidth < 540 || bigAnchorHeight < 960) {
                smallAnchorWidth = 120;
                smallAnchorHeight = 180;
                offsetHeight = 60;
            }
            //组装混流JSON结构体
            var streamInfoArray = [];
            if (mergeStreams && mergeStreams.length > 0) {
                var bigAnchorInfo = {//大主播
                input_stream_id: this.bigAnchorStreamID || '',
                layout_params: {
                    image_layer: 1,
                    input_type:4
                }
            }
            streamInfoArray.push(bigAnchorInfo);
            //小主播
            var subLocationX = bigAnchorWidth - smallAnchorWidth;
            var subLocationY = bigAnchorHeight - smallAnchorHeight - offsetHeight;
            if (mergeStreams && mergeStreams.length > 0) {
                var layerIndex = 0
                mergeStreams.forEach(function (val) {
                    var smallAchorInfo = {//组装JSON
                        input_stream_id: val.streamID,
                        layout_params: {
                            image_layer: layerIndex + 2,
                            image_width: smallAnchorWidth,
                            image_height: smallAnchorHeight,
                            location_x: subLocationX,
                            location_y: subLocationY - layerIndex * smallAnchorHeight,
                            input_type:4
                        }
                    }
				    streamInfoArray.push(smallAchorInfo);
				    layerIndex++;
                });
            }
            } else {
                var bigAnchorInfo = {
                    input_stream_id: this.bigAnchorStreamID || '',
                    layout_params: {
                        image_layer: 1
                    }
                }
                streamInfoArray.push(bigAnchorInfo);
            }
            var para = {
                app_id: '1400255047',
                interface: 'mix_streamv2.start_mix_stream_advanced',
                mix_stream_session_id: this.bigAnchorStreamID,
                output_stream_id: this.bigAnchorStreamID,
                input_stream_list: streamInfoArray
            }
            var interfaceObj = {
                interfaceName: 'Mix_StreamV2',
                para: para
            }
            var reqParam = {
                timestamp: Math.round((Date.now() / 1000)),
                eventId: Math.round((Date.now() / 1000)),
                interface: interfaceObj
            }
            return reqParam;
        },
        doMergeRequest(mergeInfo, callback){
            var data = {
                userID:this.unserinfo.user_id,
                roomID:this.RoomInfoos.roomID,
                mergeParams:JSON.stringify(mergeInfo),
                token:localStorage.getItem('token')
            }
            this.$axios({
                method:'post',
                url:'https://liveroom.qcloud.com/weapp/live_room/merge_stream',
                params:data,
                data: data,
            }).then((res) =>{
                console.log(res.data,'连线成功')
               if (res.data.merge_msg == "Success!") {
                    console.log('1')
                    callback(true);
                }else{
                    console.log('2')
                    console.error('混流失败:', JSON.stringify(res));
                    callback(false);
                    return;
                }
            }).catch((error) =>{
                console.log(error)
            })
        },
        submit() {
            // 确认弹窗回调
            this.show = false
        }
    },   
    components: {//组件注册
        Footer,
        Head,
        Modal 
    },
}
</script>
<style lang="less" scoped>
    .Voicebroadcast-content{
        position: relative;
        width: 100%;
        min-width: 1400px;
        height: 1000px;
        margin: 0 auto;
        background:rgba(241,241,241,1);
        display: flex;
        align-items: center;
    }
    .Voicebroadcast-con-content{
        position: relative;
        width: 1400px;
        height: 853px;
        margin: 0 auto;
        background:rgba(43,53,71,1);
        border-radius: 20px;
    }
    .Voicebroadcast-info{
        position: relative;
        width: 90%;
        height: 80px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        color: #fff;
        padding-top: 30px;
        div{
            width: 50%;
            height: 80px;
        }
    }
    .Voicebroadcast-info-left{
        width: 50%;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
    }
    .Voicebroadcast-info-left>span{
        display: inline-block;
        width: 100%;
        color: #29E1E2;
        font-weight: bold;
        font-size: 24px;
    }
    .Voicebroadcast-info-left>label{
        display: inline-block;
        width: 100%;
        span{
            display: inline-block;
            color: #C4CEE1;
            font-size: 16px;
            &:first-child{
                background-image: url('/images/语言icon@2x.png');
                background-repeat: no-repeat;
                background-size: 14px 13px;
                background-position-y: 50%;
                padding-left: 4%;
            }
            &:last-child{
                background-image: url('/images/人物icon@2x.png');
                background-repeat: no-repeat;
                background-size: 14px 13px;
                background-position-y: 50%;
                padding-left: 4%;
                margin-left: 4%;
            }
        }
    }  
    .Voicebroadcast-info-right{
        justify-content: flex-end;
        display: flex;
        width: 50%;
        align-items: center;
       span{
           display: inline-block;
           width: 30%;
           text-align: center;
           color: #BDC8DB;
           font-size: 16px;
        }
        label{
            display: inline-block;
            width: 30%;
            height: 40px;
            line-height: 40px;
            border:1px solid rgba(71,206,207,1);
            border-radius: 20px;
            text-align: center;
            cursor: pointer;
            color: #29E1E2;
            font-size: 14px;
            background-image: url('/images/组 14@2x.png');
            background-repeat: no-repeat;
            background-position-x: 86%;
            background-position-y: 50%;
            background-size: 19px 17px;
        }
    }
    .Voicebroadcast-contents{
        position: relative;
        width: 90%;
        margin: 0 auto;
        height: 80%;
        display: flex;
        align-items: center;
        margin-top: 20px;
    }
    .Voicebroadcast-contents-left{
        width: 70%;
        height: 100%;
    }
    .Voicebroadcast-contents-right{
        width: 30%;
        height: 100%;
        background:#141D2D;
    }
    .Voicebroadcast-avater{
        position: relative;
        width: 80%;
        height: 80%;
        margin: 0 auto;
        display: flex;
        align-items: center;
        margin-left: 6%;
        flex-wrap: wrap;
    }
    .Voicebroadcast-avater>div{
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-wrap: wrap;
        label{
            width: 100%;
            text-align: center;
            img{
                width: 150px;
                height: 150px;
                border-radius: 100px;
            }
        }
        span{
            width: 100%;
            text-align: center;
            color: #ffffff;
            font-size: 20px;
        }
    }
    .Voicebroadcast-avater>ul{
        position: relative;
        width: 100%;
        height: 80%;
        margin:  0 auto;
        display: flex;
        margin-top: 30px;
        list-style: none;
        padding: 0;
        flex-wrap: wrap;
        justify-content: space-between;
        li{
            width: 150px;
            height: 150px;
            background:#19212E;
            border-radius: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
    }
    .noattachment{
        width: 24px;
        height: 36px;
    }
    .attachment{
        width: 100%;
        height: 100%;
    }
    .Voicebroadcast-footer{
        position: relative;
        width: 100%;
        height: 20%;
        display: flex;
        align-items: flex-end;
        label{
            width: 33%;
            height: 100%;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            img{
                cursor: pointer;
            }
        }
    }
    .Voicebroadcast-footer>label:first-child{
        span{
            color: #BDC8DB;
            font-size: 18px;
            display: inline-block;
            height: 40px;
            line-height: 40px;
            padding-left: 14%;
            background-image: url('/images/圆角矩形 30@2x.png');
            background-repeat: no-repeat;
            background-size: 27px 30px;
            width: 100%;
        }
    }
    .attachment>span{
        text-align: center;
        width: 103px;
        height: 36px;
        line-height: 36px;
        background: #ffffff;
        border-radius: 20px;
        cursor: pointer;
    }
    .Voicebroadcast-footer>label:last-child{
        img{
            width: 18px;
            height: 16px;
            margin-left: 10%;
            &:first-child{
                width: 13px;
                height: 19px;
            }
            &:last-child{
                width: 20px;
                height: 19px;
            }
        }
    }


    .Systemmessage{
        position: relative;
        width: 90%;
        margin: 0 auto;
        margin-top: 20px;
        p{
            color: #2DC7C8;
            font-size: 12px;
            &:last-child{
                line-height: 20px;
                letter-spacing: 4px;
            }
        }
    }
    .messagefooter{
        position: relative;
        width: 341px;
        margin: 0 auto;
        height: 90px;
        background:rgba(255,255,255,1);
        position: absolute;
        right: 20px;
        bottom: 20px;
        border-radius: 5px;
    }
    .messagefooter>label{
        display: inline-block;
        width: 100%;
        height: 20%;
    }
    .messagefooter>div>textarea{
        display: inline-block;
        border: none;
        height: 100%;
        width: 70%;
        outline: none;
        resize: none;
        overflow:hidden;
        padding-left: 4%;
    }
    .messagefooter>div>span{
        display: inline-block;
        width: 54px;
        height: 30px;
        text-align: center;
        background: #2B3547;
        border-radius: 10px;
        line-height: 30px;
        margin-left: 80%;
        cursor: pointer;
        color: #ffffff;
        font-size: 12px;
    }
    .MessageList{
        position: relative;
        width: 90%;
        height: 60%;
        margin: 0 auto;
        padding: 0;
        overflow: auto;
        list-style: none;
        ::-webkit-scrollbar{
            width: 1px;  
            background-color: #F5F5F5;  
        }
        li{
            height: 40px;
            line-height: 40px;
            width: 100%;
            span{
                font-size: 12px;
                &:first-child{
                    color: #2DC7C8;
                }
                &:last-child{
                    color: #FFFFFF;
                    margin-left: 4%;
                }
            }
        }
    }
    .vcp-player{
        border-radius: 100px;
    }
   
</style>